package com.qf.compusdemo.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

@Component("MyAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {


        String currentUser = authentication.getName();
        logger.info("用户"+currentUser+"登录成功");
        HttpSession session=request.getSession();
        session.setAttribute("username",currentUser);
        session.setAttribute("auth",authentication.getAuthorities());
        UUID uuid = UUID.randomUUID();
        String token = uuid.toString();
        request.getSession().setAttribute("token",token);
        //响应的时候把token写入cookie中
        Cookie cookie = new Cookie("myshop-token",token);
        cookie.setPath("/");
        cookie.setMaxAge(60*60);
        response.addCookie(cookie);
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().append("{\"code\":0,\"msg\":\"登录成功!\",\"data\":\"success\",\"token\":\"12345\"}");
        if(session.getAttribute("auth").toString().contains("admin")){
            response.sendRedirect("/view/main.jsp");
        }
        else{    response.sendRedirect("/view/mainnormal.jsp");}


    }
}
